from transformers.models.bert.modeling_bert import *
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss


class RobertaForPreTraining(BERTPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.config = config

        self.bert = BertModel(config)
        self.cls = BertPreTrainingHeads(config)
        self.classifier = nn.Linear(config.hidden_size, 2)

        # Initialize weights and apply final processing
        self.post_init()

    def forward(
            self,
            input_ids: Optional[torch.LongTensor] = None,
            attention_mask: Optional[torch.FloatTensor] = None,
            token_type_ids: Optional[torch.LongTensor] = None,
            position_ids: Optional[torch.LongTensor] = None,
            head_mask: Optional[torch.FloatTensor] = None,
            inputs_embeds: Optional[torch.FloatTensor] = None,
            sentence_labels: Optional[torch.LongTensor] = None,
            mlm_labels: Optional[torch.LongTensor] = None,
            replace_labels: Optional[torch.LongTensor] = None,
            output_attentions: Optional[bool] = None,
            output_hidden_states: Optional[bool] = None,
            return_dict: Optional[bool] = None,
    ) -> Tuple[torch.Tensor | None, torch.Tensor, torch.Tensor]:
        r"""
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.bert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        sequence_output, pooled_output = outputs[:2]
        mlm_scores, sentence_score = self.cls(sequence_output, pooled_output)
        replace_logits = self.classifier(sequence_output[0])
        loss_fct = CrossEntropyLoss()

        replace_loss = None
        if replace_labels is not None:
            # move labels to correct device to enable model parallelism
            replace_labels = replace_labels.to(replace_logits.device)
            replace_loss = loss_fct(replace_logits.view(-1, 2), replace_labels.view(-1))
        total_loss = None
        if mlm_labels is not None:
            masked_lm_loss = loss_fct(mlm_scores.view(-1, self.config.vocab_size), mlm_labels.view(-1))
            total_loss = masked_lm_loss
        if sentence_labels is not None:
            sequence_loss = loss_fct(sentence_score.view(-1, 2), sentence_labels.view(-1))
            if total_loss is None:
                total_loss = sequence_loss
            else:
                total_loss += sequence_loss
        if replace_loss is not None:
            total_loss += replace_loss

        return total_loss, sentence_score, pooled_output
